import React, { useState, useEffect } from 'react';
import { Button, Table, message, Input, Tooltip } from 'antd';
import services from '../../../services/api';
import './typeManage.less'

export default function TypeManage(props) {
  const { interfaceType, onChange } = props;
  const [data, setData] = useState([]);

  useEffect(() => {
    getDataSourceTypeOptions();
  }, []);

  // 获取接口分组/数据源类型
  const getDataSourceTypeOptions = async () => {
    const { data, code, msg } = await services.dataSourceType.list(interfaceType);
    if (!code) {
      setData(data);
      onChange(data);
    } else {
      message.error(msg);
    }
  };

  const handleAdd = () => {
    const type_obj = {
      name: '',
      type: true, // true为input框 false 为label值
      isAdd: true
    };
    const temp = [...data];
    temp.unshift(type_obj);
    setData(temp);
  };

  const handleRename = (type, index) => {
    const temp = [...data];
    temp[index].type = !type;
    temp[index]['old_name'] = temp[index].name;
    setData(temp);
  };

  const handleDelete = async (code) => {
    const res = await services.dataSourceType.delete(code, interfaceType);
    if (!res.code) {
      message.success(res.msg);
      getDataSourceTypeOptions();
    } else {
      message.error(res.msg);
    }
  };

  const handleCancel = (index, record) => {
    const { isAdd, type } = record
    const temp = [...data];
    if (isAdd) {
      temp.splice(index, 1);
    } else {
      temp[index].type = !type;
      temp[index].name = temp[index].old_name;
    }
    setData(temp);
  };

  const handleInputChange = (value, index) => {
    const temp = [...data];
    temp[index].name = value;
    setData(temp);
  };

  const handleCodeChange = (value, index) => {
    value = value.replace(/[^A-Za-z_0-9]/g, '')
    const temp = [...data];
    temp[index].code = value;
    setData(temp);
  };

  const handleSumbit = async (record, index) => {
    const { code, name, isAdd } = record
    if (!code) return message.warning('请输入接口分组code！');
    if (!name) return message.warning('请输入接口分组名称！');
    let msg = ''
    for (let i = 0; i < data.length; i++) {
      if (i !== index) {
        if (data[i].code === code) {
          msg = '接口分组code重复'
          break
        } else if (data[i].name === name) {
          msg = '接口分组名称重复'
          break
        }
      }
    }
    if (msg) return message.warn(msg)
    const params = {
      code,
      name,
      interfaceType,
    };
    const res = !isAdd
      ? await services.dataSourceType.update(params)
      : await services.dataSourceType.add(params);
    if (!res.code) {
      message.success(res.msg);
      getDataSourceTypeOptions();
    } else {
      message.error(res.msg);
    }
  };

  const columns = [
    {
      title: 'code',
      dataIndex: 'code',
      ellipsis: true,
      width: 300,
      render: (text, record, index) =>
        record.isAdd ? (
          <Input
            value={text}
            onChange={(e) => handleCodeChange(e.target.value, index)}
            onPressEnter={(e) => handleSumbit(record, index)}
            placeholder='限英文数字下滑线'
          />
        ) : (
          <Tooltip title={text} placement='topLeft'>
            {text}
          </Tooltip>
        ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (text, record, index) =>
        record.type ? (
          <Input
            value={text}
            onChange={(e) => handleInputChange(e.target.value, index)}
            onPressEnter={(e) => handleSumbit(record, index)}
          />
        ) : (
          <Tooltip title={text} placement='topLeft'>
            {text}
          </Tooltip>
        ),
    },
    {
      title: '操作',
      width: 100,
      render: (_, record, index) => (
        <>
          {!record.type ? (
            <>
              <Button type='link' onClick={() => handleRename(record.type, index)}>
                重命名
              </Button>
              <Button type='link' onClick={() => handleDelete(record.code)}>
                删除
              </Button>
            </>
          ) : (
            <>
              <Button type='link' onClick={() => handleSumbit(record, index)}>
                确定
              </Button>
              <Button type='link' onClick={() => handleCancel(index, record)}>
                取消
              </Button>
            </>
          )}
        </>
      ),
    },
  ];

  return (
    <div>
      <Button onClick={handleAdd}>添加</Button>
      <Table
        className="fixed"
        columns={columns}
        dataSource={data}
        rowKey={(record, index) => index}
        pagination={false}
        scroll={{x: false, y: 500}}
      />
    </div>
  );
}
